package com.ruiysoft.controller.mdse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.controller.mdse.util.MdseVoUtil;
import com.ruiysoft.controller.mdse.vo.SpuDtoVo;
import com.ruiysoft.controller.mdse.vo.SpuListVo;
import com.ruiysoft.entity.aftersaleconf.AftersaleConfSpuRela;
import com.ruiysoft.entity.mdse.MerchandiseSku;
import com.ruiysoft.entity.mdse.MerchandiseSpu;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.mapper.mdse.MerchandiseSkuMapper;
import com.ruiysoft.pub.consts.EnumUtil;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.aftersaleconf.IAftersaleConfSpuRelaService;
import com.ruiysoft.service.mdse.IMerchandiseManage;
import com.ruiysoft.service.mdse.IMerchandiseSpuService;
import com.ruiysoft.service.mdse.bean.MerchandiseCondition;
import com.ruiysoft.service.mdse.bean.MerchandiseSpuDto;
import com.ruiysoft.service.mdse.bean.SkuDtail;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.*;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-10-27T01:43:53.483+08:00")

@RestController
public class MdseApiController implements MdseApi {

    private static final Logger log = LoggerFactory.getLogger(MdseApiController.class);

    private final IMerchandiseManage mdseManage;
    @Resource
    private IMerchandiseSpuService spuService;

    @Resource
    private  IAftersaleConfSpuRelaService spuRelaService;
    @org.springframework.beans.factory.annotation.Autowired
    public MdseApiController(IMerchandiseManage mdseManage) {
        this.mdseManage = mdseManage;
    }

    @Autowired
    MerchandiseSkuMapper merchandiseSkuMapper;

    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        if(personnel != null)
            return personnel.getId();

        return null;
    }

    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    @Override
    public Result<Void> mdseDelPost(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "spuIds", required = true) List<Long> spuIds) {
        Long shopId = getShopId();
        try {
            mdseManage.delBySpuIds(spuIds,shopId);
            spuRelaService.remove(new QueryWrapper<AftersaleConfSpuRela>().in("spu_id",spuIds));
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺删除商品--{}--{}--{}",shopId,spuIds, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

//    @Cacheable(value = "mdseQuerySpuListGet")
    @Override
    public Result<PageInfo<SpuListVo>> mdseQuerySpuListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "分类id") @Valid @RequestParam(value = "categoryId", required = false) Long categoryId, @ApiParam(value = "商品名") @Valid @RequestParam(value = "mdseName", required = false) String mdseName, @ApiParam(value = "上下架状态（0，上架，1，下架）") @Valid @RequestParam(value = "status", required = false) Integer status) {
        Long shopId = getShopId();
        MerchandiseCondition condition = new MerchandiseCondition();
        condition.setPageIndex(pageStart);
        condition.setPageSize(pageSize);
        condition.setDelFlag(EnumUtil.DelFlag.NO.getIndex());
        condition.setCategoryId(categoryId).setMdseName(mdseName).setStatus(status).setShopId(shopId);

        try {
            PageInfo<MerchandiseSpuDto> page = mdseManage.findspuDtoPageByCondition(condition);

            List<SpuListVo> list = new ArrayList<>();
            page.getList().forEach(spuDto->{
                SpuListVo vo = null;
                try {
                    vo = MdseVoUtil.spuDtoToSpuListVo(spuDto);
                    list.add(vo);

                } catch (Exception e) {
                    log.error("spuDtoToSpuListVo--{}",JSONObject.toJSONString(spuDto), e);
                }
            });

            // 按 sequence 排序
            Collections.sort(list, new Comparator<SpuListVo>() {
                @Override
                public int compare(SpuListVo o1, SpuListVo o2) {
                    if(o1.getSequence() != null && o2.getSequence() != null) {
                        int diff = o1.getSequence() - o2.getSequence();
                        if (diff > 0)
                            return 1;
                        else {
                            if (diff < 0)
                                return -1;
                        }
                    }

                    return 0;
                }
            });

            return ResultGenerator.genSuccessResult(new PageInfo<SpuListVo>(list, page));

        } catch (Exception e) {
            log.error("店铺查询商品列表---{}--{}",shopId,JSONObject.toJSONString(condition), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Long> mdseSavePost(@ApiParam(value = ""  )  @Valid @RequestBody SpuDtoVo body) {
        Long shopId = getShopId();
        Long userId = getUserId();
        try {
            //校验修改时店铺id是否一致
            if(body.getSpuId()!=null){
                MerchandiseSpu spu = spuService.getById(body.getSpuId());
                if(spu!=null&&!Objects.equals(spu.getShopId(),shopId)){
                    throw new IllegalArgumentException("登录店铺不是此商品所属店铺");
                }
            }
            MerchandiseSpuDto spuDto = MdseVoUtil.spuDtoVoToSpuDto(body);
            spuDto.getSpu().setShopId(shopId);
            spuDto.getSpu().setUpdator(userId);
            mdseManage.sava(spuDto);
            return ResultGenerator.genSuccessResult(spuDto.getSpu().getSpuId());
        } catch (Exception e) {
            log.error("保存商品失败---{}--{}--{}",shopId,userId,JSONObject.toJSONString(body), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<SpuDtoVo> mdseSpuDetailByIdSpuIdGet(@ApiParam(value = "",required=true) @PathVariable("spuId") Long spuId) {
        Long shopId = getShopId();
        try {
            MerchandiseSpuDto spuDto = mdseManage.findMdseSpuDtoBySpuId(spuId,shopId);
            return ResultGenerator.genSuccessResult(MdseVoUtil.spuDtoToSpuDtoVo(spuDto));
        } catch (Exception e) {
            log.error("商铺获取spu详情--{}--{}",shopId,spuId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> mdseStatusStatusPost(@ApiParam(value = "上下架状态（1，上架，2，下架）",required=true) @PathVariable("status") Integer status, @NotNull @ApiParam(value = "", required = true) @Valid @RequestBody List<Long> spuIds) {
        Long shopId = getShopId();
        try {
            mdseManage.upAllStatus(spuIds,status,shopId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺上下架商品--{}--{}--{}",shopId,status,spuIds, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> mdseStatusStatusByCategoryIdPost(Integer status, @Valid Long categoryId) {
        Long shopId = getShopId();
        try {
            mdseManage.upAllStatusByCategoryIdPost(status,shopId,categoryId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺上下架商品--{}--{}--{}",shopId,status, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<SkuDtail> querySkuList(Long spuId) {
        Result result = null;
        Long shopId = getShopId();
        List<SkuDtail> list = mdseManage.querySkuList(shopId, spuId);
        if(list != null)
            result = ResultGenerator.genSuccessResult(list);
        else
            result = ResultGenerator.genFailResult("没有查询到记录!");

        return result;
    }

    // 新建商品
    @Override
    public Result<Void> insertOrUpdateSku(@NotNull @Valid SkuDtail skuDtail) {
        Result result = null;
        Long shopId = getShopId();
        skuDtail.setShopId(shopId);
        skuDtail.setUpdateTime(new Date());
        skuDtail.setDelFlag(0);
        // 默认下架
        skuDtail.setStatus(2);

        /*
        // 元转分
        if(skuDtail.getListPrice() != null)
            skuDtail.setListPrice(skuDtail.getListPrice() * 100);
        if(skuDtail.getUnitPrice() != null)
            skuDtail.setUnitPrice(skuDtail.getUnitPrice() * 100);
        */

        int rtn = mdseManage.createOrEditSku(skuDtail);
        if(rtn >= 0)
            result = ResultGenerator.genSuccessResult(rtn);
        else
            result = ResultGenerator.genFailResult("操作失败!");

        return result;
    }

    @Override
    public Result<Void> delSku(@NotNull @Valid Integer skuId) {
        Result result = null;

        int rtn = mdseManage.delSku(skuId);
        if(rtn >= 0)
            result = ResultGenerator.genSuccessResult(rtn);
        else
            result = ResultGenerator.genFailResult("操作失败!");

        return result;
    }

    @Override
    public Result<Void> updateSpu(@NotNull @Valid MerchandiseSpu merchandiseSpu) {
        Result result = null;
        Long shopId = getShopId();
        merchandiseSpu.setShopId(shopId);

        merchandiseSpu.setUpdateTime(new Date());
        int rtn = mdseManage.updateSpu(merchandiseSpu);
        if(rtn >= 0)
            result = ResultGenerator.genSuccessResult(rtn);
        else
            result = ResultGenerator.genFailResult("操作失败!");

        return result;
    }

    @Override
    public Result<Void> upOrDownSku(@RequestParam(value = "skuId", required = true) Integer skuId, @RequestParam(value = "upOrDown", required = true) Integer upOrDown) {

        MerchandiseSku merchandiseSku = merchandiseSkuMapper.selectById(skuId);
        if(merchandiseSku != null) {
            merchandiseSku.setUpdateTime(new Date());
            // 1 上架 2下架
            merchandiseSku.setStatus(upOrDown);
            int rtn = merchandiseSkuMapper.updateById(merchandiseSku);
            if(rtn > 0)
                return ResultGenerator.genSuccessResult(null);
        }

        return ResultGenerator.genFailResult("操作失败!");
    }

    @Caching(evict = {
        @CacheEvict(value = "wxMdseSkuListGet", allEntries = true),
        @CacheEvict(value = "wxMdseDetailSkuIdGet", allEntries = true),
        @CacheEvict(value = "getSlideModelByShopId", allEntries = true),
        @CacheEvict(value = "categoryListGet", allEntries = true),
        @CacheEvict(value = "getloginOnUser", allEntries = true),
        @CacheEvict(value = "mdseQuerySpuListGet", allEntries = true)
    })
    @Override
    public Result<Void> clearCache(String key) {
        return new Result<Boolean>().setBizCode(ResultCode.CODE_SUCCESS);
    }
}
